package com.dmgis.qxfw.utils;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.*;

public class SoapUtil {
    /**
     * 解析SOAP返回数据
     * @param response
     * @param table
     * @return
     */
    public static List<Map<String, String>> responseWebList(String response, String table) {
        //创建Reader对象
        SAXReader reader = new SAXReader();
        //加载xml
        Document document = null;
        List<Map<String, String>> requestList = new ArrayList<>();
        Map<String, String> request = new HashMap();
        try {
            //获取数据流
            InputStream is = new ByteArrayInputStream(response.getBytes());
            document = reader.read(is);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        //获取根节点
        Element rootElement = document.getRootElement();
        Iterator iterator = rootElement.elementIterator();
        while (iterator.hasNext()) {
            Element stu = (Element) iterator.next();
            //判断节点是否为Result 如果不是则向下遍历
            while (!stu.getName().equals((table + "Result"))) {
                if (stu.elementIterator().hasNext()) {
                    stu = (Element) stu.elementIterator().next();
                } else {
                    return null;
                }
            }
            System.out.println("responseWebList: ======遍历子节点======");
            Iterator iterator1 = stu.elementIterator();
            while (iterator1.hasNext()) {
                Element stuChild = (Element) iterator1.next();
                if (stuChild.elementIterator().hasNext()) {
                    System.out.println("responseWebList: ======遍历孙节点======");
                    Iterator iterator2 = stuChild.elementIterator();
                    request = new HashMap();
                    while (iterator2.hasNext()) {
                        Element stuSon = (Element) iterator2.next();
                        System.out.println("节点名：" + stuSon.getName() + "---节点值：" + stuSon.getStringValue());
                        request.put(stuSon.getName(), stuSon.getStringValue());
                    }
                }
                requestList.add(request);
            }
        }
        return requestList;
    }
}
